package com.wt.chat.service.impl;

import com.wt.chat.cache.RedisCache;
import com.wt.chat.entity.Dialog;
import com.wt.chat.entity.Group;
import com.wt.chat.exception.BaseException;
import com.wt.chat.mapper.CompanyMapper;
import com.wt.chat.mapper.DialogMapper;
import com.wt.chat.mapper.GroupMapper;
import com.wt.chat.model.DialogModel;
import com.wt.chat.query.PageQuery;
import com.wt.chat.service.DialogService;
import com.wt.chat.utils.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @description
 * @author: wangtao
 * @date:13:43 2019/11/12
 * @email:taow02@jumei.com
 */
@Service
public class DialogServiceImpl implements DialogService {

	@Autowired
	private DialogMapper dialogMapper;

	@Autowired
	private GroupMapper groupMapper;

	@Autowired
	private RedisCache redisCache;

	@Override
	public List<DialogModel> currentDialog(Dialog condition) {
		return dialogMapper.findByCondition(condition);
	}

	@Override
	public List<DialogModel> historyDialog(Dialog condition, PageQuery pageQuery) {
		return dialogMapper.findHistory(condition, pageQuery);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void inQueue(Dialog dialog) {
		Group group = groupMapper.selectByPrimaryKey(dialog.getGroupId());
		if (group == null) {
			throw new BaseException("不正确的进线组");
		}
		dialog.setCompanyId(group.getCompanyId());
		dialogMapper.insertSelective(dialog);
		redisCache.rightPush(Keys.getDialogQueueByGroup(group.getId() + ""), dialog);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void close(Dialog dialog) {
		Integer dialogId = dialog.getId();
		Dialog dbDialog = dialogMapper.selectByPrimaryKey(dialogId);
		if (dbDialog.getStatus() == Dialog.DialogStatus.CLOSE.getValue()) {
			// 如果会话已经关闭，不做处理
			return;
		}
		redisCache.del(Keys.getDialogMessageRedisKey(dialogId + ""));
		dialogMapper.updateByPrimaryKeySelective(dialog.setEndTime(new Date()).setStatus(Dialog.DialogStatus.CLOSE.getValue()));
	}
}
